﻿/*
 Copyright (c) 2011-2012 Aaron Zhang
 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:
 
 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.
 
 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 SOFTWARE.
*/

using KBCruiser.Configuration;
using KBCruiser.Controls;
using System;
using System.Diagnostics;
using System.IO;
using System.Windows.Forms;

namespace KBCruiser.Forms
{
    public partial class Mainform : Form
    {
        private TabPage tpBrowser;
        private Browser browser;

        public Mainform()
        {
            InitializeComponent();
            RegisterEvents();
            InitializeFavorite();
            InitializeSearcher();
        }

        private void InitializeFavorite()
        {
            string favorite = Environment.GetFolderPath(Environment.SpecialFolder.Favorites);
            if (Directory.Exists(favorite))
            {
                ToolStripMenuItem item = new ToolStripMenuItem();
                item.Text = "Favorite";

                GetMenuItem(favorite, item);
                menuStripMain.Items.Add(item);
            }
        }

        private void GetMenuItem(string path, ToolStripMenuItem item)
        {
            string[] dirs = Directory.GetDirectories(path);
            foreach (string dir in dirs)
            {
                ToolStripMenuItem stripMenuItem = new ToolStripMenuItem();
                int index = dir.LastIndexOf('\\');
                stripMenuItem.Text = dir.Substring(index + 1);
                item.DropDownItems.Add(stripMenuItem);
                GetMenuItem(dir, stripMenuItem);
            }

            string[] files = Directory.GetFiles(path);
            foreach (string file in files)
            {
                ToolStripMenuItem stripMenuItem = new ToolStripMenuItem();
                int index = file.LastIndexOf('\\');
                int externsionIndex = file.LastIndexOf('.');
                stripMenuItem.Text = file.Substring(index + 1, externsionIndex - index - 1);
                stripMenuItem.Tag = file;
                stripMenuItem.Click += new EventHandler(stripMenuItemFavorite_Click);
                item.DropDownItems.Add(stripMenuItem);
            }
        }

        private void InitializeSearcher()
        {
            Profile currentProfile = ConfigRepository.Instance.CurrentProfile;

            foreach (KBCruiser.Configuration.Menu menu in currentProfile.Menus)
            {
                ToolStripMenuItem item = new ToolStripMenuItem();
                item.Text = menu.Name;
                foreach (KBCruiser.Configuration.MenuItem menuItem in menu.Items)
                {
                    ToolStripMenuItem stripMenuItem = new ToolStripMenuItem();
                    stripMenuItem.Text = menuItem.Name;
                    stripMenuItem.Tag = menuItem;
                    stripMenuItem.Click += new EventHandler(stripMenuItem_Click);
                    item.DropDownItems.Add(stripMenuItem);
                }
                menuStripMain.Items.Add(item);
            }
            menuStripMain.Items.Add(helpToolStripMenuItem);

            foreach(SearchCategory category in currentProfile.Categories)
            {
                TabPage tp = new TabPage();
                tp.Name = category.Name;
                tp.Text = category.Name;
                tp.UseVisualStyleBackColor = true;
                ReferencePane pane = new ReferencePane();
                tp.Controls.Add(pane);
                pane.Dock = DockStyle.Fill;
                pane.UrlChanged += new ReferencePane.UrlChangedEventHandler(pane_UrlChanged);
                foreach (SearcherConfig searcher in category.Searchers)
                {
                    pane.AddSearcher(searcher);
                }
                tcMain.TabPages.Add(tp);
            }
            tpBrowser = new TabPage();
            tpBrowser.Name = "Browser";
            tpBrowser.Text = "Browser";
            tpBrowser.UseVisualStyleBackColor = true;
            browser = new Browser();
            browser.Dock = DockStyle.Fill;
            tpBrowser.Controls.Add(browser);
            tcMain.TabPages.Add(tpBrowser);
        }

        private void pane_UrlChanged(object sender, UrlChangedEventArgs e)
        {
            txtSearch.Text = e.Url;
        }

        private void RegisterEvents()
        {
            this.btnSearch.Click += new System.EventHandler(this.btnSearch_Click);
            this.txtSearch.KeyDown += new KeyEventHandler(txtSearch_KeyDown);
        }

        private void stripMenuItem_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem item = sender as ToolStripMenuItem;
            if (item != null)
            {
                KBCruiser.Configuration.MenuItem menuItem = item.Tag as KBCruiser.Configuration.MenuItem;
                if (menuItem != null)
                {
                    if (menuItem.Action == "Browse")
                    {
                        browser.Navigate(menuItem.Target);
                        tcMain.SelectedTab = tpBrowser;
                    }
                    else if (menuItem.Action == "Start")
                    {
                        Process.Start(menuItem.Target, menuItem.Parameter);
                    }
                }
            }
        }

        private void stripMenuItemFavorite_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem item = sender as ToolStripMenuItem;
            if (item != null)
            {
                string file = item.Tag as string;
                if (file != null)
                {
                    using (StreamReader reader = new StreamReader(file))
                    {
                        string line = null;
                        while ((line = reader.ReadLine()) != null)
                        {
                            if (line.StartsWith("URL=", StringComparison.InvariantCultureIgnoreCase))
                            {
                                if (line.Length > 4)
                                {
                                    browser.Navigate(line.Substring(4));
                                    tcMain.SelectedTab = tpBrowser;
                                }
                            }
                        }
                    }
                }
            }
        }

        private void txtSearch_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                PerformSearch();
            }
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            PerformSearch();
        }

        private void PerformSearch()
        {
            string searchTarget = txtSearch.Text.Trim();
            if (!string.IsNullOrEmpty(searchTarget))
            {
                ReferencePane pane = tcMain.SelectedTab.Controls[0] as ReferencePane;
                if (pane != null)
                {
                    pane.Search(searchTarget);
                }
            }
        }

        private void aboutToolStripMenuItemAbout_Click(object sender, EventArgs e)
        {
            using (About about = new About())
            {
                about.ShowDialog();
            }
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void clearToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ReferencePane pane = tcMain.SelectedTab.Controls[0] as ReferencePane;
            if (pane != null)
            {
                pane.ClearCheckBox();
            }
        }
    }
}
